package com.example.mybatisplus;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Properties;
import org.apache.logging.log4j.util.PropertiesUtil;

public class CodeGenerator {

    public static String getProjectConfig(String key) {
        Properties pros = new Properties();
        String value = "";
        try {
            pros.load(new InputStreamReader(PropertiesUtil.class.getResourceAsStream("/application.yml"), "UTF-8"));
            value = pros.getProperty(key);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return value;
    }

    public static void main(String[] args) {

        //当前项目路径
        String projectPath = System.getProperty("user.dir");

        //输出路径
        String fileOutputPath = projectPath.concat("/src/main/java");
        String mapperOutputPath = projectPath.concat("/src/main/resources/mapper");

        //这里获取的是配置文件的DB参数;
        String url = getProjectConfig("url");
        String username = getProjectConfig("username");
        String password = getProjectConfig("password");

        //生成代码
        FastAutoGenerator.create(url, username, password)
            .globalConfig(builder -> {
                builder.author("lizhien") // 设置作者
                    .disableOpenDir() // 禁止打开目录
                    .enableSwagger() // 开启 swagger 模式
                    .fileOverride() // 覆盖已生成文件
                    .outputDir(fileOutputPath); // 指定输出目录
            })
            .packageConfig(builder -> {
                builder.parent("com.example.mybatisplus") // 设置父包名
                    .moduleName("") // 设置父包模块名
                    .pathInfo(Collections.singletonMap(OutputFile.mapperXml, mapperOutputPath)); // 设置mapperXml生成路径
            })
            .strategyConfig(builder -> {
                builder.addExclude("test") // 设置需要生成的表名
                    .addTablePrefix("t_", "c_"); // 设置过滤表前缀
            })
//            .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板，默认的是Velocity引擎模板
            .execute();
    }
}
